<!--
 * @Author: weidewei
 * @Date: 2025-05-12 09:41:10
 * @LastEditors: weidewei
 * @LastEditTime: 2025-10-31 18:03:30
 * @Description: 
 * @FilePath: \2025-front-face\js\事件循环.html
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件循环</title>
  </head>
  <body>
    <script>
      // 1.什么是事件循环： js是单线程的，但是可以通过事件循环来实现异步操作。
      // 2.事件循环执行的过程是：同步代码执行完，然后异步代码放到任务队列当中，然后等待同步代码执行完，然后再从任务队列当中取出异步代码执行。
      // 3.执行的顺序是：同步代码-》微任务（promise.then promise.nextTick Object.observe MutationObserver）-》宏任务（setTimeout setInterval setImmediate）

      //   console.log("1"); // 同步

      //   setTimeout(() => console.log("2")); // 宏任务

      //   Promise.resolve().then(() => console.log("3")); // 微任务

      //   requestAnimationFrame(() => console.log("4")); // rAF

      //   console.log("5"); // 同步

      //   输出的是1,5,3,4,2 4和2 有时会调换位置
      console.log("============================");

      console.log("1");
      console.log("2");
      // new Promise((resolve,reject)=>{
      //     console.log("3")
      //     resolve()
      // }).then(()=>{
      //     console.log("4")
      // })
      Promise.resolve().then(() => {
        console.log("4");
      });
      setTimeout(() => {
        console.log("5");
      }, 0);
      // setInterval(()=>{
      //     console.log("6")
      // })

      console.log("xxxxxxxxxxxxxxxxxxxxx");

      setTimeout(function func1() {
        console.log(1);
        a();
      }, 0);

      function a() {
        setTimeout(function func2() {
          console.log(2);
        }, 0);
        console.log(3);
      }

      a();

      console.log(4);

      // 3 4 1 3 2 2

      // 题目 1​​（基础：微任务 vs 宏任务）输出结果：start，end，promise2，timeout1，promise1，timeout2
      console.log("start");

      setTimeout(() => {
        console.log("timeout1");
        Promise.resolve().then(() => console.log("promise1"));
      }, 0);

      Promise.resolve().then(() => {
        console.log("promise2");
        setTimeout(() => console.log("timeout2"));
      });

      console.log("end");

      // ​题目 2​​（Node.js 特性：process.nextTick优先级最高）输出：start,end,promise,nextTick,timeout 错 答案：start,end,nextTick,promise,timeout
      console.log("start");

      setTimeout(() => console.log("timeout"), 0);
      Promise.resolve().then(() => console.log("promise"));
      process.nextTick(() => console.log("nextTick"));

      console.log("end");

      // 题目 3​​（async/await中的微任务）输出：start，foo start，foo end，end,promise,timeout 错 答案：start，foo start,end,foo end,promise,timeout await不会阻塞同步代码，而是将 await后的代码包装成微任务，等待同步代码执行完后再执行
      console.log("start");

      async function foo() {
        console.log("foo start");
        await Promise.resolve(); // 等价于 Promise.then(...)
        console.log("foo end");
      }

      foo();

      setTimeout(() => console.log("timeout"), 0);
      Promise.resolve().then(() => console.log("promise"));

      console.log("end");

      // 题目 4​​（多宏任务与微任务交织）输出：1，6，4，2，3，5
      console.log("1");

      setTimeout(() => {
        console.log("2");
        Promise.resolve().then(() => console.log("3"));
      }, 0);

      Promise.resolve().then(() => {
        console.log("4");
        setTimeout(() => console.log("5"));
      }, 0);

      console.log("6");

      // 题目 5​​（setImmediate与 process.nextTick 输出：start,end,nextTick,immediate,timeout 错 答案：start,end,nextTick,timeout,immediate Node.js 的事件循环阶段顺序是：timers→ poll→ check。setTimeout(fn, 0)属于 timers阶段（延迟 0ms，进入 timers队列）。 setImmediate()属于 check阶段（专门处理 setImmediate回调）。
      console.log("start");

      setImmediate(() => console.log("immediate"));
      process.nextTick(() => console.log("nextTick"));
      setTimeout(() => console.log("timeout"), 0);

      console.log("end");

      // 题目 6​​（事件循环阶段：I/O 回调与微任务）输出：start，end,nextTick,fs callback,promise in io,timeout,immediate in io 错：start,end,nextTick,timeout,fs callback,promise in io,immediate in io
      const fs = require("fs");

      console.log("start");

      fs.readFile(__filename, () => {
        // 模拟 I/O 回调（属于 poll 阶段）
        console.log("fs callback");
        Promise.resolve().then(() => console.log("promise in io"));
        setImmediate(() => console.log("immediate in io"));
      });

      setTimeout(() => console.log("timeout"), 0);
      process.nextTick(() => console.log("nextTick"));

      console.log("end");


      
    </script>
  </body>
</html>
